<template>
    <view class="content">
        <van-nav-bar :title="scrolling? navBarTitle : '' " left-arrow @click-left="onClickLeft"> </van-nav-bar>

        <scroll-view class="scroll-content" scroll-y :lower-threshold="80" @scroll="scrollPage" show-scrollbar="false">

            <view class="tabTop">
                <view class="title"> {{navBarTitle}}</view>
                <form >
                    <view class="userInfoBox">
                        <!-- required clearable  -->
                        <van-field class="uni-input" label="姓名" focus placeholder="请输入您的姓名" @change="changeName"
                            placeholder-style="color:#888888; font-size:12px;" hold-keyboard="true"
                            custom-style="color:#111111; font-size:14px;" :value="userInfo.realName"
                            :border="noBorder" />
                        <van-field class="uni-input" label="手机号" focus placeholder="请输入您的手机号" @input="handlePhoneInput"
                            @change="changeNumber" :value="userInfo.phone" :border="noBorder" type="number"
                            hold-keyboard="true" custom-style="color:#111111; font-size:14px;" />
                        <van-field class="uni-input" label="所在地址" focus placeholder="请输入您的地址" @change="changeAddress"
                            :value="userInfo.detail" :border="noBorder" hold-keyboard="true"
                            custom-style="color:#111111; font-size:14px;" disabled>
                            <van-icon slot="right-icon" name="location" size="20" />
                        </van-field>
                        <van-field class="uni-input" label="详细地址" focus placeholder="请输入您的小区名称、具体门牌号"
                            @change="changeDoorNumber" :value="userInfo.houseNumber" :border="noBorder"
                            hold-keyboard="true" custom-style="color:#111111; font-size:14px;" disabled/>
                    </view>
                    <!-- <view class="userInfoBox" v-else>
                        <van-field class="uni-input" focus placeholder="请输入您的姓名" @change="changeName"
                            placeholder-style="color:#888888; font-size:12px;" hold-keyboard="true"
                            custom-style="color:#111111; font-size:14px;" :value="userInfo.realName"
                            :border="noBorder" />
                        <van-field class="uni-input" focus placeholder="请输入您的电话" @input="handlePhoneInput"
                            @change="changeNumber" :value="userInfo.phone" :border="noBorder" type="number"
                            hold-keyboard="true" custom-style="color:#111111; font-size:14px;" />
                        <van-field class="uni-input" focus placeholder="请输入您的地址" @change="changeAddress"
                            :value="userInfo.detail" :border="noBorder" hold-keyboard="true"
                            custom-style="color:#111111; font-size:14px;" disabled>
                        </van-field>
                        <van-field class="uni-input" focus placeholder="请输入您的小区名称 具体门牌号 （不可更改）"
                            @change="changeDoorNumber" :value="userInfo.houseNumber" :border="noBorder"
                            hold-keyboard="true" custom-style="color:#111111; font-size:14px;" disabled />
                    </view> -->

                    <view class="defaultBox">
                        <view class="setDefault">设置为默认地址</view>
                        <van-switch :checked="userInfo.isDefault" @change="onChange" active-color="#FF6203"
                            inactive-color="#e6e6e6" size="36rpx"></van-switch>
                    </view>
                    <view class="pasteAddress" v-if="this.params.handle==='add'">
                        <view class="pasteTitle">智能识别</view>
                        <view class="pasteText">
                            <view style="min-height: 150rpx;">
                                <textarea placeholder="点击粘贴信息，可自动识别粘贴信息" :value="clipboardData"
                                    placeholder-style="font-size: 12px;color: #888888;" :disable-default-padding="true"
                                    @input="handleInput" auto-focus="true" confirm-type="done" maxlength="200"
                                    autoHeight custom-style="font-size: 12px;line-height:2; color:#888888;"
                                    @paste="handlePaste" adjust-position >
                                </textarea>
                            </view>
                            <view class="pasteButton" @tap="getClipboardData">粘贴并识别地址</view>
                        </view>
                    </view>
                    <view class=" btn-area">
                        <!-- <button style="margin: 30px 0" type="waring" plain form-type="submit" class="button">保存并使用</button> -->
                        <van-button type="primary" form-type="submit" @click="formSubmit" :disabled="submitLock"
                          :class="{ 'disabled-btn': submitLock }">保存并使用</van-button>
                    </view>
                </form>
            </view>


        </scroll-view>
        <van-toast id="van-toast" />

    </view>
</template>

<script>
import {updateUserAddressApi,addUserAddressApi} from '@/api/mine'
export default {
    data() {
        return {
            navBarTitle: '编辑信息',
            scrolling:false,
            userInfo:{
                realName:'王涛员',
                phone:'15632632541',
                address:'山西省 运城市 盐湖区',
                detail:'',
                houseNumber:'',
                isDefault:false,
                latitude:'',
                longitude:''
            },
            noBorder:false,
            params:undefined, //接受从路由传过来的参数
            pageBiaoshi:'',
            clipboardData:undefined,
            showTip: true,
            submitLock: false, // 新增防抖锁
        }
    },
    onLoad(data) {
        if(data!==null){
            this.params=JSON.parse(decodeURIComponent(data.params))
            console.log(this.params)
            this.pageBiaoshi=this.params.pageBiaoshi
            if(this.pageBiaoshi==='my'){
                if(this.params.handle==='add'){
                    this.navBarTitle='新增地址'
                    this.userInfo = {
                        userName: undefined,
                        phone: undefined,
                        address: undefined,
                        door_number: undefined
                    }
                }else if(this.params.handle==='edit'){
                    this.navBarTitle='编辑地址'
                    this.userInfo = this.params.item
                }
            }else{
                this.navBarTitle='编辑信息'
                this.userInfo = this.params.item
                this.userInfo.address =this.params.item.province + this.params.item.city
                if (this.params.item.isDefault && (this.params.item.isDefault === 1 || this.params.item.isDefault === true)) {
                    this.userInfo.isDefault = true
                } else {
                    this.userInfo.isDefault = false
                }
            }
        }
    },
    methods: {
        // 滑动
        scrollPage(e) {
            console.log(e.detail.scrollTop, this.scrolling)
            if (e.detail.scrollTop > 25 && !this.scrolling) {
                this.scrolling = true
            } else if ((e.detail.scrollTop <= 25 && this.scrolling) || (e.detail.scrollTop <= 25 && !this.scrolling)) {
                this.scrolling = false
            }
        },
        // 返回键
        onClickLeft () {
            uni.navigateBack()
        },
        // 默认按钮  switch
        onChange(e){
            console.log(e,'e')
            this.userInfo.isDefault=e.detail
        },
        // 修改名字
        changeName(e){
            console.log(e.detail,'修改名字')
            this.userInfo.realName=e.detail
        },
        // 修改电话
        handlePhoneInput(e){
            const inputValue = e.detail;
            const phoneRegex = /^1[3-9]\d{9}$/;
            // console.log(e,'输入手机号')
            if (!phoneRegex.test(inputValue)) {
                // this.userInfo.phone = inputValue.replace(/[^\d]/g, '');
                uni.showToast({
                    icon: 'none', // 不显示图标，最多显示2行
                    title: '手机号格式不正确',
                    // duration: 2000
                })
                console.log('请输入正确的手机号')
            } else {
                this.userInfo.phone = inputValue;
            }
        },
        changeNumber(event){
            const inputValue = event.detail;
            const phoneRegex = /^1[3-9]\d{9}$/;
            // console.log(event,'输入手机号')
            if (!phoneRegex.test(inputValue)) {
                // this.userInfo.phone = inputValue.replace(/[^\d]/g, '');
                uni.showToast({
                    icon: 'none', // 不显示图标，最多显示2行
                    title: '请输入正确的手机号',
                    // duration: 2000
                })
                console.log('请输入正确的手机号')
            } else {
                this.userInfo.phone = inputValue;
            }
        },

        changeAddress(){},
        
        changeDoorNumber(){},
        handlePaste(event) {
            const pasteText = event.clipboardData.getData('text');
            // 这里可以添加地址识别的逻辑
            console.log('粘贴的内容:', pasteText);
        },
        pasteAndRecognize() {
            // 模拟点击输入框触发粘贴事件
            const input = this.$refs.input;
            input.dispatchEvent(new Event('paste'));
        },
        // 复制粘贴并自动识别
        getClipboardData() {
            wx.getClipboardData({
                success: (res) => {
                    console.log(res,'res00000')
                    this.clipboardData= res.data
                    // 假设地址格式为：姓名+电话+地址，使用空格分割
                    let parts = res.data.split('↵');
                    console.log(parts,'parts')
                    if (parts.length >= 3) {
                        this.userInfo.userName= parts[0],
                        this.userInfo.phone= parts[1],
                        this.userInfo.door_number= parts.slice(2).join(' ')
                    }
                    // 在这里可以添加对获取到的内容进行识别和处理的逻辑
                    // 例如，如果是地址信息，可以使用正则表达式等方式进行解析
                    wx.showToast({
                        title: '获取到内容：' + res.data,
                        icon: 'none',
                        duration: 2000
                    });
                },
                fail: (err) => {
                    console.error('获取剪贴板内容失败：', err);
                    wx.showToast({
                        title: '获取剪贴板内容失败',
                        icon: 'none',
                        duration: 2000
                    });
                }
            });
        },

        // submit
        formSubmit(e) {
            if (this.submitLock) return;
            this.submitLock = true;
            // console.log('form发生了submit事件，携带数据为：', e.detail.value)
            console.log(this.userInfo,'this.userInfo','被点击了')
            const { realName, phone,detail, isDefault } = this.userInfo;
            if (!realName || !phone || !detail) {
                uni.showToast({
                    title: '请填写完整信息',
                    icon: 'none'
                });
                this.submitLock = false;
                return;
            }
            const phoneRegex = /^1[3-9]\d{9}$/;
            if (!phoneRegex.test(phone)) {
                uni.showToast({
                    icon: 'none', // 不显示图标，最多显示2行
                    title: '请输入正确的手机号',
                    // duration: 2000
                })
                this.submitLock = false;
            } else {
                updateUserAddressApi({
                    id: this.userInfo.id, // 地址ID，编辑时需要传递
                    realName: this.userInfo.realName,
                    phone: this.userInfo.phone,
                    provinceName: this.userInfo.provinceName,
                    cityName: this.userInfo.cityName,
                    districtName: this.userInfo.districtName,
                    detail:this.userInfo.detail, //所在区域 地图返回的长的地址
                    houseNumber: this.userInfo.houseNumber, // 门牌号
                    isDefault: this.userInfo.isDefault,
                    latitude: this.userInfo.latitude,
                    longitude: this.userInfo.longitude,
                    postCode: this.userInfo.postCode || undefined,//邮编
                }).then(res => {
                    console.log(res,'res')
                    if (res.code === 200) {
                        uni.showToast({
                            icon: 'success', //最多显示7个汉字长度
                            // icon: 'none', // 不显示图标，最多显示2行
                            title: '编辑地址成功',
                            duration: 3000
                        })
                        setTimeout(() => {
                            // 3秒后执行页面跳转，这里假设跳转到名为 'otherPage' 的页面，需确保该页面已在小程序的页面配置中存在
                            uni.navigateBack()
                        }, 3000);
                    } else {
                        uni.showToast({ icon: 'none', title: res.msg || '提交失败' });
                    }
                }).finally(() => {
                    setTimeout(() => uni.navigateBack(), 3000)
                    this.submitLock = false
                });

            }

        },
    }
}
</script>

<style scoped>
.content {
    background-color: #ffffff;
    display: flex;
    flex-direction:column;
    height:100vh;
    overflow:hidden;
    box-sizing: border-box;
}
.scroll-content {
    flex: 1;
    height: 1px;
}
.tabTop{
    padding:0px 48rpx;
}
.title{
    font-size: 60rpx;
    line-height: 60rpx;
    text-align: left;
    color: #111111;
}
.userInfoBox{
    margin-top: 70rpx;
}

.uni-input {
    /* background: #EEF7FE; */
    height: 53px;
    /* border-bottom: 1px solid #f9f9f9; */
}
.tips{
    font-size: 12px;
    text-align: left;
    color: #888888;
}
.defaultBox{
    margin-top: 24px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.setDefault{
    font-size: 24rpx;
    text-align: left;
    color: #888888;
}
.pasteAddress{
    margin-top: 52rpx;
}
.pasteTitle{
    color: #111111;
    font-size: 28rpx;
    line-height: 28rpx;
}
/* 粘贴地址 */
.pasteText{
    margin-top: 28rpx;
    padding: 24rpx;
    background-color: rgba(247,247,247,1);
    /* width: 100%; */
    min-height: 264rpx;
}
/* 按钮 */
.pasteButton{
    float: right;
    color: rgba(255,98,3,1);
    font-size: 24rpx;
    line-height: 24rpx;
    height: 24rpx;
    cursor: pointer;
}
.disabled-btn {
    border-color: #cccccc !important;
}
/* .btn-area{
    position: fixed;
    bottom: 0;
    padding-bottom: calc(32rpx + env(safe-area-inset-bottom));
    width: calc(100% - 96rpx);
} */


/* .container {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.tip-box {
  width: 300px;
  height: 200px;
  background-color: #f0f0f0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.tip-text {
  font-size: 16px;
  color: #999;
  text-align: center;
}
.btn-text {
  font-size: 16px;
  color: orange;
  margin-left: auto;
  cursor: pointer;
} */

::v-deep .van-button--primary {
    width: 100%;
    height: 86rpx;
    border-radius: 38rpx;
    font-size: 28rpx;
    background: #FF6203 !important;
    border: 1px solid #ff6203 !important;
}

::v-deep .van-nav-bar__left {
    width: 56px;
    height: 44px;
}

::v-deep .van-icon {
    color: #242629 !important;
}
::v-deep .van-cell{
    padding-left: 0px !important;
    border-bottom: 1px solid #f9f9f9;
}

</style>
